<template>
    <div class="relative w-full bg-white/96 rounded-xl shadow-lg overflow-hidden">
        <div class="w-full bg-[#2B6E50] py-2">
            <span class="text-white text-[18px] font-bold ml-5">物联网数据显示</span>
        </div>
        <div class="px-2 py-5 overflow-y-auto ">
            <div class="grid grid-cols-3 gap-4">
                <div class="flex flex-col items-center cursor-pointer hover:bg-gray-100 p-2 rounded"
                    v-for="item in iconList" :key="item.name" @click="openModal(item)">
                    <img class="w-10 h-10" :src="item.icon" />
                    <span class="text-gray-800 text-sm text-center mt-1">{{ item.name }}</span>
                </div>
            </div>
        </div>

        <!-- 遮罩弹窗 -->
        <div v-if="showModal" class="absolute inset-0 rounded-lg bg-black/50 flex items-center justify-center"
            @click="closeModal">
            <div class="bg-white rounded-lg w-[100%] h-[100%] relative" @click.stop >
                <div class="flex justify-between items-center w-full absolute left-0 z-50 px-4">
                  <p class="py-1"> {{ selectedIndicator }}变化趋势</p>
                    <div class="flex items-center gap-4">
                        <el-select v-model="selectedIndicator" @change="onIndicatorChange" class="!w-[120px]" size="small">
                            <el-option v-for="item in iconList" :key="item.name" :label="item.name"
                                :value="item.name" />
                        </el-select>
                        <el-icon :size="12" @click="closeModal" class="text-gray-500 hover:text-gray-700 cursor-pointer">
                            <Close />
                        </el-icon>
                    </div>
                </div>
                <div v-loading="loading" class="w-full h-full pt-10">
                    <LineChart :title="selectedIndicator + '变化趋势'" :x-axis-data="chartData.xAxis"
                        :data="chartData.data" :y-axis-name="getCurrentUnit()" height="calc(100%)" />
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import LineChart from '../forest-management/components/LineChart.vue'
import { getLineData } from '@/api/forest-management'
import icon1 from '@/assets/icons/icon1.png'
import icon2 from '@/assets/icons/icon2.png'
import icon3 from '@/assets/icons/icon3.png'
import icon4 from '@/assets/icons/icon4.png'
import icon5 from '@/assets/icons/icon5.png'
import icon6 from '@/assets/icons/icon6.png'
import icon7 from '@/assets/icons/icon7.png'
import icon8 from '@/assets/icons/icon8.png'
import icon9 from '@/assets/icons/icon9.png'

interface IconItem {
  icon: string
  name: string
  key: string
  unit: string
}

interface SeriesData {
  name: string
  data: number[]
  color: string
}

interface ChartData {
  xAxis: string[]
  data: number[] | SeriesData[]
}

interface DataPoint {
  time: string
  value: number
}

interface ApiResponse {
  data: DataPoint[]
}

const iconList = [
    { icon: icon1, name: '风速',key:'windSpeed',unit:'m/s'},
    { icon: icon2, name: '风向',key:'windDirection',unit:'°' },
    { icon: icon3, name: '空气温度',key:'temperature' ,unit:'℃'},
    { icon: icon4, name: '空气湿度',key:'airHumidity' ,unit:'%'},
    { icon: icon5, name: '降雨量' ,key:'hourRainfall',unit:'mm'},
    { icon: icon6, name: '大气压力' ,key:'atmosphericPressure',unit:'hPa'},
    { icon: icon7, name: '土壤水分',key:'soilWaterPct' ,unit:'%'},
    { icon: icon8, name: '土壤湿度',key:'soilMoisture' ,unit:'℃'},
    { icon: icon9, name: '光照度' ,key:'maxSunshine',unit:'w/m²'}
]

const showModal = ref(false)
const loading = ref(false)
const selectedItem = ref<IconItem | null>(null)
const selectedIndicator = ref('')
const chartData = ref<ChartData>({
    xAxis: [],
    data: []
})

const openModal = (item: IconItem) => {
    selectedItem.value = item
    selectedIndicator.value = item.name
    showModal.value = true
    fetchChartData()
}

const closeModal = () => {
    showModal.value = false
    selectedItem.value = null
}

const getCurrentUnit = (): string => {
    const currentItem = selectedItem.value || iconList.find(item => item.name === selectedIndicator.value)
    // return selectedIndicator.value + currentItem?.unit || ''
    return  ''
}

const formatTime = (timeStr: string): string => {
    return timeStr.replace(/^\d{4}-(\d{2}-\d{2} \d{2}:\d{2}):\d{2}$/, '$1')
}

const onIndicatorChange = async (value: string) => {
    const item = iconList.find(item => item.name === value)
    if (item) {
        selectedItem.value = item
        // 强制清空数据并重置图表实例
        chartData.value = { xAxis: [], data: [] }
        // 添加延迟确保图表完全重置
        await new Promise(resolve => setTimeout(resolve, 50))
        await fetchChartData()
    }
}

const fetchChartData = async () => {
    try {
        loading.value = true
        // 清空之前的数据
        chartData.value = { xAxis: [], data: [] }

        const currentItem = selectedItem.value || iconList.find(item => item.name === selectedIndicator.value)
        if (!currentItem) return

        // 土壤水分和土壤温度需要调用3次接口
        if (currentItem.name === '土壤水分' || currentItem.name === '土壤温度') {
            const [data1, data2, data3] = await Promise.all([
                getLineData(currentItem.name === '土壤温度'?currentItem.key + '1':currentItem.key),
                getLineData(currentItem.key + '2'),
                getLineData(currentItem.key + '3')
            ])

            const response1 = data1 as ApiResponse
            const response2 = data2 as ApiResponse
            const response3 = data3 as ApiResponse

            chartData.value = {
                xAxis: response1.data.map((v) => formatTime(v.time)) || [],
                data: [
                    { name: `${currentItem.name}1`, data: response1.data.map((v) => v.value) || [], color: '#5470c6' },
                    { name: `${currentItem.name}2`, data: response2.data.map((v) => v.value) || [], color: '#91cc75' },
                    { name: `${currentItem.name}3`, data: response3.data.map((v) => v.value) || [], color: '#fac858' }
                ]
            }
        } else {
            const response = await getLineData(currentItem.key) as ApiResponse
            chartData.value = {
                xAxis: response.data.map((v) => formatTime(v.time)) || [],
                data: response.data.map((v) => v.value) || []
            }
        }
    } catch (error) {
        console.error('获取图表数据失败:', error)
    } finally {
        loading.value = false
    }
}
</script>
